package com.farmpost.ssoservice.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.farmpost.ssoservice.security.CustomAuthorityDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户基本信息
 * </p>
 *
 * @author king
 * @since 2022-04-03
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class UserInfo implements Serializable, UserDetails {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private Integer userId;

    private String username;

    private String userPassword;

    private Integer stuId;

    @Getter(AccessLevel.NONE) // 不需要生成 get 方法，防止与 UserDetails 重写的 isEnabled 冲突
    private Integer enable;

    private Integer userLogout;

    private String sex;

    private Integer age;

    private String userFace;

    private LocalDate createDate;

    private String other;

    @TableField(exist = false)
    private List<Role> roles;

    /**
     * 获取权限列表
     * role.getName() 权限名字
     * 角色里面对应的名字，把它转成 SimpleGrantedAuthority 返回
     *
     * @return
     */
    @Override
    @JsonDeserialize(using = CustomAuthorityDeserialize.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (null == roles) {
            return Collections.emptySet();
        }
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getRoleName()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return userPassword;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enable == 0;//0表示未禁用
    }

}
